package com.seari.groovyrunner.bean;

import com.alibaba.fastjson.JSON;
import com.seari.groovyrunner.config.Constants;
import com.seari.groovyrunner.service.GroovyLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class GroovyLogAspect {

    @Autowired
    public GroovyLogService groovylogService;



    @Pointcut("@annotation(com.seari.groovyrunner.bean.GroovyLogInterfacce)")
    public void groovyLogPointCut(){}

    @AfterReturning(value = "groovyLogPointCut()",returning = "keys")
    public void saveGroovyLog(JoinPoint joinPoint,Object keys){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        GroovyLogInterfacce annotation = method.getAnnotation(GroovyLogInterfacce.class);
        String modul =null;
        String type =null;
        String desc =null;
        if (annotation!=null){
            modul = annotation.logModul();
            type = annotation.logType();
            desc = annotation.logDesc();
        }
        String className = joinPoint.getTarget().getClass().getName()+"."+method.getName();
        String params = converMap(request.getParameterMap());
        String requestURI = request.getRequestURI().substring(Constants.baseUrl.length());
        groovylogService.addGroovyLog(modul,type,desc,requestURI,className,params,(ReturnBean)keys);
    }

    private String converMap(Map<String, String[]> parameterMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : parameterMap.keySet()) {
            rtnMap.put(key, parameterMap.get(key)[0]);
        }
        return rtnMap.isEmpty()?"":JSON.toJSONString(rtnMap);
    }
}
